package thread;

public class SyncDemo1 {
    static boolean success1=false;
    static boolean success2=false;
    public static void main(String[] args) {
        Bank bank=new Bank();
        int sum=0;
        while (true){
            sum++;
        Thread t1=new Thread(){
            public void run(){
                success1=bank.getMoney(20000);
            }
        };
        Thread t2=new Thread(){
            public void run(){
                success2=bank.getMoney(20000);
            }
        };
        t1.start();
        t2.start();
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if (success1&&success2){
            System.out.println("转账成功"+sum+"次");
            break;
        }else {
            success1=false;
            success2=false;
            bank.setAccount(20000);
        }
        }
    }
}

class Bank{
    private int account=20000;
    public synchronized boolean getMoney(int money){
        int account=getAccount();
        if (account>=money){
            account=account-money;
            setAccount(account);
            return true;
        }
        return false;
    }
    public void setAccount(int account) {
        this.account = account;
    }
    public int getAccount() {
        return account;
    }
}